package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.leihao.bo.BrandListDTO;
import com.cskaoyan.bean.leihao.bo.CategoryDTO;
import com.cskaoyan.bean.leihao.bo.ChildrenDTO;
import com.cskaoyan.bean.leihao.po.CreatePo;
import com.cskaoyan.bean.leihao.po.Update;
import com.cskaoyan.bean.leihao.vo.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Auther: leihao
 * @Date: Created in 14:00 2022/6/27
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;
    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketCommentMapper commentMapper;

    /**
     * 从market_goods表中查询商品信息
     *
     * @Auther leihao
     * @Date 15:54 2022/6/27
     * @Param basePageInfo 页面限制信息，包含了当前页以及数据数目限制信息
     * @Return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.MarketGoods>
     **/
    @Override
    public CommonData<MarketGoods> getGoodsList(BasePageInfo basePageInfo, Integer goodsId, String goodsSn, String name) {
        // 开启分页
        if(basePageInfo.getLimit()==0){
            PageHelper.startPage(1,basePageInfo.getLimit());
        }else {
            PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        }

        // 创建example对象，添加准则
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if (goodsId != null) {
            criteria.andIdEqualTo(goodsId);
        }
        if (goodsSn != null) {
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        // 调用mapper查询数据库
        List<MarketGoods> list = goodsMapper.selectByExampleWithBLOBs(marketGoodsExample);
        // 获取分页信息
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(list);

        // 封装数据返回结果
        return CommonData.data(pageInfo);
    }

    /**
     * 从market_goods,market_goods_attribute,market_goods_product
     * market_goods_specification四张表中查找商品信息
     *
     * @Auther leihao
     * @Date 10:24 2022/6/28
     * @Param
     * @Return
     **/

    @Override
    public GoodsDetailVo getGoodsDetail(Integer id) {
        MarketGoods goods = goodsMapper.selectByPrimaryKey(id);

        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria = marketGoodsAttributeExample.createCriteria();
        criteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(marketGoodsAttributeExample);

        //String[]
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria1 = marketGoodsProductExample.createCriteria();
        criteria1.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> products = productMapper.selectByExample(marketGoodsProductExample);

        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specifications = specificationMapper.selectByExample(marketGoodsSpecificationExample);


        List<Integer> categoryIds = new ArrayList<>();

        Integer categoryId = goods.getCategoryId();
        MarketCategory marketCategory = categoryMapper.selectByPrimaryKey(categoryId);
        if(marketCategory!=null){
            categoryIds.add(marketCategory.getPid());
        }

        categoryIds.add(goods.getCategoryId());

        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setAttributes(attributes);
        goodsDetailVo.setCategoryIds(categoryIds);
        goodsDetailVo.setGoods(goods);
        goodsDetailVo.setProducts(products);
        goodsDetailVo.setSpecifications(specifications);

        return goodsDetailVo;
    }

    /**
     * 响应market_brand和market_category表中的id和name值作为value和label
     *
     * @Auther leihao
     * @Date 10:20 2022/6/28
     * @Param
     * @Return
     **/
    @Override
    public CatAndBrandVo getCatAndBrand() {
        //构建brandList
        List<BrandListDTO> brandList = brandMapper.selectMarketBrandIdAndName();

        //构建categoryList
        ArrayList<CatAndBrandVo.CategoryListDTO> categoryList = new ArrayList<CatAndBrandVo.CategoryListDTO>();
        List<CategoryDTO> categoryDTOS = categoryMapper.selectCategoriesIdAndName();

        for (int i = 0; i < categoryDTOS.size(); i++) {

            List<ChildrenDTO> children = categoryMapper.selectIdAndNameByPid(categoryDTOS.get(i).getValue());
            CatAndBrandVo.CategoryListDTO category = new CatAndBrandVo.CategoryListDTO();
            category.setValue(categoryDTOS.get(i).getValue());
            category.setLabel(categoryDTOS.get(i).getLabel());
            category.setChildren(children);
            categoryList.add(category);
        }
        //构建CatAndBrandVo
        CatAndBrandVo catAndBrandVo = new CatAndBrandVo();
        catAndBrandVo.setBrandList(brandList);
        catAndBrandVo.setCategoryList(categoryList);
        return catAndBrandVo;
    }

    /**
     * 从market_goods,market_goods_attribute,market_goods_product
     * market_goods_specification四张表中删除商品信息
     *
     * @Auther leihao
     * @Date 10:19 2022/6/28
     * @Param
     * @Return
     **/

    @Override
    public void deleteGoodsById(MarketGoods marketGoods) {
        int i = goodsMapper.deleteByPrimaryKey(marketGoods.getId());

        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andGoodsIdEqualTo(marketGoods.getId());
        int i1 = productMapper.deleteByExample(productExample);

        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria1 = attributeExample.createCriteria();
        criteria1.andGoodsIdEqualTo(marketGoods.getId());
        int i2 = attributeMapper.deleteByExample(attributeExample);

        MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
        MarketGoodsSpecificationExample.Criteria criteria2 = specificationExample.createCriteria();
        criteria2.andGoodsIdEqualTo(marketGoods.getId());
        int i3 = specificationMapper.deleteByExample(specificationExample);
        if (marketGoods.getBrandId() != null) {
            int i4 = brandMapper.deleteByPrimaryKey(marketGoods.getBrandId());
        }
        if (marketGoods.getCategoryId() != null) {
            int i5 = categoryMapper.deleteByPrimaryKey(marketGoods.getCategoryId());
        }
    }

    /**
     * 更新商品信息到market_goods,market_goods_attribute,market_goods_product
     * market_goods_specification四张表中
     *
     * @Auther leihao
     * @Date 10:16 2022/6/28
     * @Param
     * @Return
     **/
    @Override
    public void update(Update update) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andIdEqualTo(update.getGoods().getId());
        int i = goodsMapper.updateByExampleWithBLOBs(update.getGoods(), marketGoodsExample);

        List<MarketGoodsAttribute> attributes = update.getAttributes();
        for (int j = 0; j < attributes.size(); j++) {
            MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
            MarketGoodsAttributeExample.Criteria criteria1 = attributeExample.createCriteria();
            criteria1.andIdEqualTo(attributes.get(j).getId());
            int i1 = attributeMapper.updateByExample(attributes.get(j), attributeExample);
        }

        List<MarketGoodsProduct> products = update.getProducts();
        for (int k = 0; k < products.size(); k++) {
            MarketGoodsProductExample productExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria1 = productExample.createCriteria();
            criteria1.andIdEqualTo(products.get(k).getId());
            int i1 = productMapper.updateByExample(products.get(k), productExample);
        }

        List<MarketGoodsSpecification> specifications = update.getSpecifications();
        for (int g = 0; g < specifications.size(); g++) {
            MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
            MarketGoodsSpecificationExample.Criteria criteria1 = specificationExample.createCriteria();
            criteria1.andIdEqualTo(specifications.get(g).getId());
            int i1 = specificationMapper.updateByExample(specifications.get(g), specificationExample);
        }
    }

    /**
     * 插入一条商品信息到market_goods
     * 获得goodsId后添加数据到market_goods_attribute,market_goods_product
     * market_goods_specification三张表中
     *
     * @Auther leihao
     * @Date 13:53 2022/6/28
     * @Param
     * @Return
     **/
    @Override
    public void create(CreatePo createPo) {
        CreatePo.GoodsDTO goods = createPo.getGoods();
        List<CreatePo.AttributesDTO> attributes = createPo.getAttributes();
        List<CreatePo.ProductsDTO> products = createPo.getProducts();
        List<CreatePo.SpecificationsDTO> specifications = createPo.getSpecifications();
        //向market_goods表中插入一条数据
        MarketGoods marketGoods = new MarketGoods();
        String[] gallery = goods.getGallery();
        // String newGallery = "[";
        // for (int i = 0; i < gallery.size(); i++) {
        //     if (i == (gallery.size() - 1)) {
        //         newGallery = newGallery + "\"" + gallery.get(i) + "\""+"]";
        //         break;
        //     }
        //     newGallery = newGallery + "\"" + gallery.get(i) + "\"" + ",";
        // }
        marketGoods.setGallery(gallery);
        marketGoods.setPicUrl(goods.getPicUrl());
        marketGoods.setIsHot(goods.getIsHot());
        marketGoods.setIsNew(goods.getIsNew());
        marketGoods.setIsOnSale(goods.getIsOnSale());
        marketGoods.setGoodsSn(goods.getGoodsSn());
        marketGoods.setName(goods.getName());
        marketGoods.setCounterPrice(goods.getCounterPrice());
        marketGoods.setUnit(goods.getUnit());
        marketGoods.setCategoryId(goods.getCategoryId());
        marketGoods.setBrandId(goods.getBrandId());
        marketGoods.setBrief(goods.getBrief());
        marketGoods.setDetail(goods.getDetail());
        Date date = new Date(System.currentTimeMillis());
        marketGoods.setAddTime(date);
        int goodsId = goodsMapper.insertSelective(marketGoods);
        //向market_goods_attribute表中插入一条数据
        for (int i = 0; i < attributes.size(); i++) {
            MarketGoodsAttribute attribute = new MarketGoodsAttribute();
            attribute.setAddTime(date);
            attribute.setGoodsId(goodsId);
            attribute.setAttribute(attributes.get(i).getAttribute());
            attribute.setValue(attributes.get(i).getValue());
            attributeMapper.insertSelective(attribute);
        }
        //向market_goods_product表中插入一条数据
        for (int k = 0; k < products.size(); k++) {
            MarketGoodsProduct product = new MarketGoodsProduct();
            product.setPrice(products.get(k).getPrice());
            product.setNumber(products.get(k).getNumber());
            product.setUrl(products.get(k).getUrl());
            product.setAddTime(date);
            // List<String> specifications1 = products.get(k).getSpecifications();
            List<String> specifications1 = products.get(k).getSpecifications();
            String[] strings = new String[specifications1.size()];
            for (int i = 0; i < specifications1.size(); i++) {
                strings[i] = specifications1.get(i);
            }
            // product.setSpecifications(specifications1.toString());
            product.setSpecifications(strings);
        }
        //向market_goods_specification表中插入一条数据
        for (int j = 0; j < specifications.size(); j++) {
            MarketGoodsSpecification specification = new MarketGoodsSpecification();
            specification.setAddTime(date);
            specification.setSpecification(specifications.get(j).getSpecification());
            specification.setValue(specifications.get(j).getValue());
            specification.setPicUrl(specifications.get(j).getPicUrl());
            specification.setGoodsId(goodsId);
        }
    }
    /**
     * @Auther leihao
     * @Date 20:30 2022/6/29
     * @Param
     * @Return
     **/
    @Override
    public Integer getGoodsCount() {
        Integer count = goodsMapper.selectCount();
        return count;
    }
    /**
     * @Auther leihao
     * @Date 20:29 2022/6/29
     * @Param
     * @Return
     **/
    @Override
    public CommonData<HotGoodsListDTO> getRelated(Integer id) {
        PageHelper.startPage(1, 6);
        Integer categoryId = goodsMapper.selectCategoryIdById(id);
        List<HotGoodsListDTO> list = goodsMapper.selectGoodsByCategoryId(categoryId);
        PageInfo<MarketCategory> pageInfo = new PageInfo(list);
        return CommonData.data(pageInfo);
    }

    /**
     * @Auther leihao
     * @Date 20:44 2022/6/29
     * @Param
     * @Return
     **/
    @Override
    public WxGoodsDetailVo getWxGoodsDetail(Integer id) {
        WxGoodsDetailVo goodsDetailVo = new WxGoodsDetailVo();

        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        goodsDetailVo.setInfo(marketGoods);

        List<IssueDTO> issue = issueMapper.selectAllIssue();
        goodsDetailVo.setIssue(issue);

        List<ProductListDTO> productList = productMapper.selectByGoodsId(id);
        goodsDetailVo.setProductList(productList);

        goodsDetailVo.setShare(true);
        goodsDetailVo.setShareImage("");
        goodsDetailVo.setUserHasCollect(0);

        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        example.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsSpecification> specificationsList = specificationMapper.selectByExample(example);
        //规格种类列表
        List<WxGoodsDetailVo.SpecificationListDTO> specificationList = new ArrayList<>();

        List<String> categoryList = specificationMapper.selectCategoryByGoodsId(id);
        for (int i = 0; i < categoryList.size(); i++) {
            WxGoodsDetailVo.SpecificationListDTO dto = new WxGoodsDetailVo.SpecificationListDTO();
            dto.setName(categoryList.get(i));
            ArrayList<MarketGoodsSpecification> valueList = new ArrayList<>();
            for (int j = 0; j < specificationsList.size(); j++) {
                if(categoryList.get(i).equals(specificationsList.get(j).getSpecification())){
                    valueList.add(specificationsList.get(j));
                    dto.setValueList(valueList);
                }
            }
            specificationList.add(dto);
        }
        goodsDetailVo.setSpecificationList(specificationList);

        WxGoodsDetailVo.CommentDTO comment = new WxGoodsDetailVo.CommentDTO();
        ArrayList<DataDTO> data = commentMapper.selectByValueId(id);
        comment.setCount(data.size());
        comment.setData(data);
        goodsDetailVo.setComment(comment);

        Byte sortOrder = goodsMapper.selectSortOrderById(id);
        MarketBrand brand = brandMapper.selectBrandBySortOrder(sortOrder);
        goodsDetailVo.setBrand(brand);

        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        attributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attribute = attributeMapper.selectByExample(attributeExample);
        goodsDetailVo.setAttribute(attribute);

        ArrayList<WxGoodsDetailVo.GrouponDTO> groupon = new ArrayList<>();
        goodsDetailVo.setGroupon(groupon);


        return goodsDetailVo;
    }
}
